package cn.vendgateway.com.config;


import org.springframework.cloud.gateway.config.GlobalCorsProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

@Configuration
public class CorsConfig {

    @Bean
    public CorsWebFilter corsWebFilter(GlobalCorsProperties globalCorsProperties) {
        CorsConfiguration config = new CorsConfiguration();
        // 允许哪些源进行跨域访问，生产中可改为指定前端域名
        config.addAllowedOriginPattern("*");
        // 是否允许发送Cookie
        config.setAllowCredentials(true);
        // 允许哪些请求方法
        config.addAllowedMethod("*");
        // 允许哪些请求头
        config.addAllowedHeader("*");
        // 暴露哪些响应头
        config.addExposedHeader("*");
        // 预检请求的有效期，单位秒。(在这个时间段内，对于相同的跨域请求不会再预检了)
        config.setMaxAge(18000L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // /** 表示对所有路径都生效
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}
